package com.sinothk.hussars.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.hussars.base.entity.PageReq;
import com.sinothk.hussars.entity.WorkerManagerEntity;
import com.sinothk.hussars.entity.WorkerAddVo;
import com.sinothk.hussars.mapper.WorkerManagerMapper;
import com.sinothk.hussars.service.WorkerManagerService;
import com.sinothk.hussars.utils.XUtils;
import com.sinothk.server.support.annotation.callback.BizException;
import com.sinothk.server.support.entity.PageData;
import com.sinothk.server.support.entity.ResultCode;
import com.sinothk.server.support.utils.IdUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 监管部门用户表 服务实现类
 * </p>
 *
 * @author liangyt
 * @since 2021-01-05
 */
@Service
public class WorkerManagerServiceImpl extends ServiceImpl<WorkerManagerMapper, WorkerManagerEntity> implements WorkerManagerService {

    @Resource
    private WorkerManagerMapper mapper;

    @Override
    public WorkerManagerEntity add(WorkerAddVo workerManagerVo) {
        // 存在验证
        LambdaQueryWrapper<WorkerManagerEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkerManagerEntity::getAccount, workerManagerVo.getAccount());
        WorkerManagerEntity dbUser = this.getOne(queryWrapper);
        if (dbUser != null) throw new BizException(ResultCode.USER_HAS_EXISTED);

        // 保存
        WorkerManagerEntity workerManager = XUtils.classUtil().copyByMethod(workerManagerVo, WorkerAddVo.class, WorkerManagerEntity.class);
        workerManager.setId(IdUtil.getIncreaseIdByNanoTime());

        Date time = new Date();
        workerManager.setCreateDate(time);
        workerManager.setUpdateDate(time);

        this.save(workerManager);
        return this.getById(workerManager.getId());
    }

    @Override
    public PageData usersPage(PageReq<WorkerManagerEntity> pageVo) {

        Page<WorkerManagerEntity> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        page.addOrder(OrderItem.desc("create_date"));
        Page<WorkerManagerEntity> userIPage = mapper.selectPage(page, Wrappers.<WorkerManagerEntity>lambdaQuery().eq(WorkerManagerEntity::getState, 0));//.like(WorkerManagerEntity::getName, "Jack")
        //
        List<WorkerManagerEntity> records = userIPage.getRecords();
        PageData pageData = new PageData();
        pageData.setPageNum(userIPage.getCurrent());
        pageData.setPageSize(userIPage.getSize());
        pageData.setCurrent(userIPage.getCurrent());
        pageData.setTotal(userIPage.getTotal());
        pageData.setData(records);
        return pageData;
    }
}
